﻿using Assets.Core.Common.Web;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Nucleic.Core.DoMain;
using Nucleic.Core.JhPay;
using Nucleic.Core.Utils;
using Nucleic.Web.Models.Bank;
using System.Web;
using NFine;
using NFine.Code;
using Newtonsoft.Json;
using System.Net;
using YinLong.Tool.Net.HttpHelperMin;
using Nucleic.Core.Utils.hebcz;
using Nucleic.Core;
using NFine.Application.User;
using WmsToVna.Util;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Nucleic.Core.WeiXinMp;
using Senparc.Weixin;

namespace Nucleic.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BankController : ControllerBase
    {
        private readonly ILogger<BankController> _logger;
        protected string AppId
        {
            get
            {
                return Config.SenparcWeixinSetting.WeixinAppId;//与微信公众账号后台的AppId设置保持一致，区分大小写。
            }
        }
        public BankController(ILogger<BankController> logger)
        {
            _logger = logger;

        }
        [HttpPost]
        [Route("TemplateBySenparc")]
        public async Task TemplateBySenparc()
        {
            TemplateApi.SendTemplateMessage(AppId,
                "o9crB08_SpbkmiS2MaT_ZRX2GNCQ", "QJM7zs35eByqO7Ys4lzeDCa6354wzRoIJgKYl2-GzVM", "",
                new
                {
                    first = new TemplateData { value = "", color = "#000000" },
                    keyword1 = new TemplateData { value = "王银龙", color = "#000000" },
                    keyword2 = new TemplateData { value = "核酸-单人单管", color = "#000000" },
                    keyword3 = new TemplateData { value = "二院", color = "#000000" },
                    keyword4 = new TemplateData { value = DateTime.Now.ToString("yyyy-MM-dd"), color = "#000000" },
                    remark = new TemplateData { value = "", color = "#000000" }
                });
        
        }
        [HttpPost]
        [Route("Template")]
        public async Task Template()
        {
           
            var token = WeiXinUtil.GetAccessToken(ConfigurationUtil.GetSection("Bank:WeixinAppId"), ConfigurationUtil.GetSection("Bank:WeixinAppSecret"));
            new WeiXinUtil().MsgPush(token, "o9crB08_SpbkmiS2MaT_ZRX2GNCQ",
                new
                {
                    first = new TemplateData { value = "", color = "#000000" },
                    keyword1 = new TemplateData { value = "王银龙", color = "#000000" },
                    keyword2 = new TemplateData { value = "核酸-单人单管", color = "#000000" },
                    keyword3 = new TemplateData { value = "二院", color = "#000000" },
                    keyword4 = new TemplateData { value = DateTime.Now.ToString("yyyy-MM-dd"), color = "#000000" },
                    remark = new TemplateData { value = "", color = "#000000" }
                }, "");
        }
        /// <summary>
        /// 建行充值回调
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("paynotice")]
        public void paynotice()
        {
            _logger.LogInformation($"建行回调[paynotice]->paynotice---------开始------------");

            var keys = Request.Form.Keys;

            Dictionary<string, string> json = new Dictionary<string, string>();
            foreach (var item in keys)
            {
                string value = Request.Form[item].ToString();
                json.Add(item, value);
            }
            keys = Request.Query.Keys;
            foreach (var item in keys)
            {
                string value = Request.Query[item].ToString();
                json.Add(item, value);
            }
            _logger.LogInformation($"建行回调[paynotice]->"+JsonConvert.SerializeObject(json));

            //通过建行返回报文中得单号获取订单模型
            var orders_id = json["ORDERID"];

            var dt = DateTime.Now;
            var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == orders_id);

            if (book != null && book.status == "0")
            {
                var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(x => x.pat_id == book.pat_id);
                //如果确实为这个订单
                if (patient!=null&& json["REMARK1"] == patient.idnum  && json["SUCCESS"] == "Y")
                {
                    _logger.LogInformation($"建行回调[paynotice]->更新预约状态订单状态" );

                    //修改预约状态
                    book.status = "1";
                    book.update_time = dt;
                    SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();

                    var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == book.item_id);
                    var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);

                    //新增订单状态
                    order_info order_ = SqlSugarFactory.Instance.Queryable<order_info>().First(x => x.orders_id == book.orders_id);
                    if (order_ == null)
                    {
                        order_ = new order_info
                        {
                            pay_time = dt,
                            pat_id = book.pat_id,
                            appo_id = book.appo_id,
                            item_id = book.item_id,
                            price = item.price,
                            num = itemtype.num,
                            orders_id = book.orders_id,
                            wx_order_no = "建行",
                            status = "0",
                            invoiceStatus = 0
                        };
                        if (patient != null)
                        {
                            order_.tel = patient.tel;
                            order_.idnum = patient.idnum;
                            order_.pat_name = patient.name;
                        }
                        SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                        _logger.LogInformation($"[{orders_id}]->充值成功->写入数据库");
                    }


                    //申请电子发票
                    
                        _logger.LogInformation($"[{orders_id}]->充值成功->申请发票");

                        mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                        {
                            einvoicespecimen = "1",
                            issuedate = dt.ToString("yyyyMMdd"),
                            issuetime = dt.ToString("hh:mm:ss"),
                            payerpartytype = "1",
                            payerpartyname = patient.name,
                            totalamount = double.Parse(item.price.ToString()).ToString(),
                            bizcode = orders_id,
                            handlingperson = hebczConst.handlingperson,
                            checker = hebczConst.checker,
                            fundpayamount = "0",
                            otherpayamount = "0",
                            accountpayamount = "0",
                            ownpayamount = double.Parse(item.price.ToString()).ToString(),
                            //relatedinvoicecode = "1253",
                            //relatedinvoicenumber = orders_id,
                        };
                        model.details.Add(new details
                        {
                            itemcode = hebczConst.item_code,
                            itemname = hebczConst.item_name,
                            itemamount = double.Parse(item.price.ToString()).ToString(),

                        });
                        model.auxdetails.Add(new auxdetails
                        {
                            auxitemrelatedcode = hebczConst.item_code,
                            auxitemrelatedname = hebczConst.item_name,
                            auxitemname = item.name,
                            auxitemamount = double.Parse(item.price.ToString()).ToString()
                        });
                        HttpHelperMin http = new HttpHelperMin();
                        HttpItemMin httpitem = new HttpItemMin()
                        {
                            URL = hebczConst.Url + "/mkomedicaleinvoice",
                            Method = "POST",
                            ContentType = "application/json",
                            Postdata = JsonConvert.SerializeObject(model),
                        };
                        var resule = http.GetHtml(httpitem);
                        _logger.LogInformation($"[{orders_id}]->充值成功->申请发票返回:" + resule.Html);

                        var invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);
                        if (invStatus != null && invStatus.code == 1)
                        {
                            //查询开票状态
                            invStatus = hebczUtil.invoicestatus(orders_id);
                            _logger.LogInformation($"[{orders_id}]->充值成功->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                            //如果没有获取过，申请电子发票
                            if (invStatus != null && invStatus.code == 1 && invStatus.data.Count > 0 && invStatus.data[0].state != "0")
                            {
                                order_.einvoicecode = invStatus.data[0].einvoicecode;
                                order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                                order_.randomnumber = invStatus.data[0].randomnumber;
                                order_.invoiceStatus = 1;
                                SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                            }

                        }

                    
                }
            }
        }
        /// <summary>
        /// 轮询-无代码
        /// </summary>
        /// <param name="orderid">订单号</param>
        /// <param name="date">2022-07-04</param>
        /// <returns></returns>
        [HttpPost]
        [Route("lunxun")]
        public Result lunxun(string? orderid,DateTime? date )
        {
            
            NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"->[轮询刷新银行状态]----------轮询开始-------");
            //查询今天状态是0的订单
            var ordersIds = SqlSugarFactory.Instance.Queryable<book_info>()
                .WhereIF(string.IsNullOrEmpty(orderid)&&!date.HasValue,it =>it.ins_time.Date >= DateTime.Now.Date && it.status == "0")

                .WhereIF(date.HasValue, it => it.ins_time.Date == date.Value.Date && it.status == "0")
                .WhereIF(!string.IsNullOrEmpty(orderid),it=>it.orders_id==orderid).Select(it => it.orders_id).ToList();

            foreach (var orders_id in ordersIds)
            {

                NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------开始-------");
                var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == orders_id);
                if (book == null)
                {
                    NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->预约信息异常-------");
                    NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                    continue;
                }
                if (book.status != "0")
                {
                    NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->订单状态不支持-------");
                    NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                    continue;
                }
                var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(i => i.pat_id == book.pat_id);
                if (patient == null)
                {
                    NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->患者信息异常-------");
                    NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                    continue;
                }

                JHRefundApp jhRefundApp = new JHRefundApp();
                xmlToolApp XMLToolApp = new xmlToolApp();
                //查询建行本订单金额
                string returnStr = jhRefundApp.GetOrder(orders_id);
                NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->患者姓名{patient.name},查询建行本订单:{returnStr}");
                //建行订单状态 成功000000
                var code = XMLToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
                NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->:患者姓名:" + patient.name + ",reutrncode:" + code);

                if (code == "000000")
                {
                    var sate = XMLToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                    //0:失败,1:成功,2:待银行确认,3:已部分退款,4:已全额退款,5:待银行确认
                    var dt = DateTime.Now;
                    if (sate == "1")
                    {
                        book.status = "1";
                        book.update_time = dt;
                        SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();
                        var TRAN_DATE = XMLToolApp.GetTextBydoc(returnStr, "TRAN_DATE");


                        var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == book.item_id);
                        var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);

                        order_info order_ = SqlSugarFactory.Instance.Queryable<order_info>().First(i => i.orders_id == book.orders_id);
                        if (order_ == null)
                        {
                            order_ = new order_info
                            {
                                pay_time = Convert.ToDateTime(TRAN_DATE),
                                pat_id = book.pat_id,
                                appo_id = book.appo_id,
                                item_id = book.item_id,
                                price = item.price,
                                num = itemtype.num,
                                orders_id = book.orders_id,
                                wx_order_no = "建行",
                                status = "0",
                                invoiceStatus = 0
                            };
                            if (patient != null)
                            {
                                order_.tel = patient.tel;
                                order_.idnum = patient.idnum;
                                order_.pat_name = patient.name;
                            }
                            SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                            NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->写入数据库");
                        }


                        //发票处理------------------------
                        //查询开票状态
                        var invStatus = hebczUtil.invoicestatus(orders_id);
                        NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                        if (invStatus.code < 1 || invStatus.data.Count == 0 || invStatus.data[0].state == "0")
                        {
                            NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->申请发票");
                            mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                            {
                                einvoicespecimen = "1",
                                issuedate = dt.ToString("yyyyMMdd"),
                                issuetime = dt.ToString("hh:mm:ss"),
                                payerpartytype = "1",
                                payerpartyname = patient.name,
                                totalamount = double.Parse(item.price.ToString()).ToString(),
                                bizcode = orders_id,
                                handlingperson = hebczConst.handlingperson,
                                checker = hebczConst.checker,
                                fundpayamount = "0",
                                otherpayamount = "0",
                                accountpayamount = "0",
                                ownpayamount = double.Parse(item.price.ToString()).ToString(),
                                //relatedinvoicecode = "1253",
                                //relatedinvoicenumber = orders_id,
                            };
                            model.details.Add(new details
                            {
                                itemcode = hebczConst.item_code,
                                itemname = hebczConst.item_name,
                                itemamount = double.Parse(item.price.ToString()).ToString(),

                            });
                            model.auxdetails.Add(new auxdetails
                            {
                                auxitemrelatedcode = hebczConst.item_code,
                                auxitemrelatedname = hebczConst.item_name,
                                auxitemname = item.name,
                                auxitemamount = double.Parse(item.price.ToString()).ToString()
                            });
                            HttpHelperMin http = new HttpHelperMin();
                            HttpItemMin httpitem = new HttpItemMin()
                            {
                                URL = hebczConst.Url + "/mkomedicaleinvoice",
                                Method = "POST",
                                ContentType = "application/json",
                                Postdata = JsonConvert.SerializeObject(model),
                            };
                            var resule = http.GetHtml(httpitem);
                            NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->申请发票返回:" + resule.Html);
                            invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);

                            if (invStatus != null && invStatus.code == 1)
                            {
                                //查询开票状态
                                invStatus = hebczUtil.invoicestatus(orders_id);
                                NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                                //如果没有获取过，申请电子发票
                                if (invStatus != null && invStatus.code == 1 && invStatus.data.Count > 0 && invStatus.data[0].state != "0")
                                {
                                    order_.einvoicecode = invStatus.data[0].einvoicecode;
                                    order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                                    order_.randomnumber = invStatus.data[0].randomnumber;
                                    order_.invoiceStatus = 1;
                                    SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                                }

                            }
                        }
                        else
                        {
                            order_.einvoicecode = invStatus.data[0].einvoicecode;
                            order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                            order_.randomnumber = invStatus.data[0].randomnumber;
                            order_.invoiceStatus = 1;
                            SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                        }

                        NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->支付成功-------");
                        NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");

                    }

                }

                Thread.Sleep(Convert.ToInt32(ConfigurationUtil.GetSection("lunxun:Sleep")));
            }
            NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"->[轮询刷新银行状态]----------轮询结束-------");

            return Result.success("没有功能");
        }
        /// <summary>
        /// 刷新订单银行状态
        /// </summary>
        /// <param name="orders_id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Status")]
        public Result Status(string orders_id)
        {
            _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------开始-------");
            var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == orders_id);
            if (book == null)
            {
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->预约信息异常-------");
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------结束-------");
                return (Result.fail("预约信息异常！"));
            }
            if (book.status != "0")
            {
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->订单状态不支持-------");
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------结束-------");
                return (Result.fail("订单状态不支持！"));
            }
            var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(i => i.pat_id == book.pat_id);
            if (patient == null)
            {
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->患者信息异常-------");
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------结束-------");
                return (Result.fail("患者信息异常！"));
            }

            JHRefundApp jhRefundApp = new JHRefundApp();
            xmlToolApp XMLToolApp = new xmlToolApp();
            //查询建行本订单金额
            string returnStr = jhRefundApp.GetOrder(orders_id);
            _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->患者姓名{patient.name},查询建行本订单:{returnStr}");
            //建行订单状态 成功000000
            var code = XMLToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
            _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->:患者姓名:" + patient.name + ",reutrncode:" + code);

            if (code == "000000")
            {
                var sate = XMLToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                //0:失败,1:成功,2:待银行确认,3:已部分退款,4:已全额退款,5:待银行确认
                var dt = DateTime.Now;
                if (sate == "1")
                {
                    var TRAN_DATE = XMLToolApp.GetTextBydoc(returnStr, "TRAN_DATE");
                    //
                    book.status = "1";
                    book.update_time = dt;
                    SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();

                    var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == book.item_id);
                    var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);

                    order_info order_ = SqlSugarFactory.Instance.Queryable<order_info>().First(i => i.orders_id == book.orders_id);
                    if (order_ == null)
                    {
                         order_ = new order_info
                        {
                            pay_time =Convert.ToDateTime(TRAN_DATE),
                            pat_id = book.pat_id,
                            appo_id = book.appo_id,
                            item_id = book.item_id,
                            price = item.price,
                            num = itemtype.num,
                            orders_id = book.orders_id,
                            wx_order_no = "建行",
                            status = "0",
                            invoiceStatus = 0
                        };
                        if (patient != null)
                        {
                            order_.tel = patient.tel;
                            order_.idnum = patient.idnum;
                            order_.pat_name = patient.name;
                        }
                        SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                        _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->写入数据库");
                    }
                    

                    //发票处理------------------------
                    //查询开票状态
                   var invStatus = hebczUtil.invoicestatus(orders_id);
                    _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                    if (invStatus.code < 1 || invStatus.data.Count == 0 || invStatus.data[0].state == "0")
                    {
                        _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->申请发票");
                        mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                        {
                            einvoicespecimen = "1",
                            issuedate = dt.ToString("yyyyMMdd"),
                            issuetime = dt.ToString("hh:mm:ss"),
                            payerpartytype = "1",
                            payerpartyname = patient.name,
                            totalamount = double.Parse(item.price.ToString()).ToString(),
                            bizcode = orders_id,
                            handlingperson = hebczConst.handlingperson,
                            checker = hebczConst.checker,
                            fundpayamount = "0",
                            otherpayamount = "0",
                            accountpayamount = "0",
                            ownpayamount = double.Parse(item.price.ToString()).ToString(),
                            //relatedinvoicecode = "1253",
                            //relatedinvoicenumber = orders_id,
                        };
                        model.details.Add(new details
                        {
                            itemcode = hebczConst.item_code,
                            itemname = hebczConst.item_name,
                            itemamount = double.Parse(item.price.ToString()).ToString(),

                        });
                        model.auxdetails.Add(new auxdetails
                        {
                            auxitemrelatedcode = hebczConst.item_code,
                            auxitemrelatedname = hebczConst.item_name,
                            auxitemname = item.name,
                            auxitemamount = double.Parse(item.price.ToString()).ToString()
                        });
                        HttpHelperMin http = new HttpHelperMin();
                        HttpItemMin httpitem = new HttpItemMin()
                        {
                            URL = hebczConst.Url + "/mkomedicaleinvoice",
                            Method = "POST",
                            ContentType = "application/json",
                            Postdata = JsonConvert.SerializeObject(model),
                        };
                        var resule = http.GetHtml(httpitem);
                        _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->申请发票返回:" + resule.Html);
                        invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);

                        if (invStatus != null && invStatus.code == 1)
                        {
                            //查询开票状态
                            invStatus = hebczUtil.invoicestatus(orders_id);
                            _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                            //如果没有获取过，申请电子发票
                            if (invStatus != null && invStatus.code == 1 && invStatus.data.Count > 0 && invStatus.data[0].state != "0")
                            {
                                order_.einvoicecode = invStatus.data[0].einvoicecode;
                                order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                                order_.randomnumber = invStatus.data[0].randomnumber;
                                order_.invoiceStatus = 1;
                                SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                            }

                        }
                    }
                    else
                    {
                        order_.einvoicecode = invStatus.data[0].einvoicecode;
                        order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                        order_.randomnumber = invStatus.data[0].randomnumber;
                        order_.invoiceStatus = 1;
                        SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                    }
                       
                    _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->支付成功-------");
                    _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------结束-------");
                    return Result.success("支付成功");
                }
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->支付失败-------");
                _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------结束-------");
                return Result.fail("支付失败");
            }
            _logger.LogInformation($"[{orders_id}]->[刷新银行状态]->支付失败-------");
            _logger.LogInformation($"[{orders_id}]->[刷新银行状态]----------结束-------");
            return Result.fail("支付失败");
        }
        /// <summary>
        /// 建行支付成功后通知
        /// </summary>
        /// <param name="orders_id">订单号</param>
        /// <returns></returns>
        [HttpPost]
        [Route("PaySuccess")]
        public Result PaySuccess(string orders_id)
        {
            var dt = DateTime.Now;
            _logger.LogInformation($"[{orders_id}]->Action[PaySuccess]->回调PaySuccess---------开始------------");
            var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == orders_id);
            if (book == null || book.status != "0")
            {
                _logger.LogInformation($"[{orders_id}]->Action[PaySuccess]->预约信息异常");

                _logger.LogInformation($"[{orders_id}]->Action[PaySuccess]->---------结束------------");

                return (Result.fail("预约信息异常！"));
            }
            //JHRefundApp jhRefundApp = new JHRefundApp();
            //xmlToolApp XMLToolApp = new xmlToolApp();
            ////查询建行本订单金额
            //string returnStr = jhRefundApp.GetOrder(orders_id);
            //_logger.LogInformation($"充值成功->[{orders_id}]->查询建行："+ returnStr);
            ////建行订单状态 成功000000
            //var code = XMLToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
            //_logger.LogInformation($"充值成功[{orders_id}]->: reutrncode:" + code);

            //if (code== "000000")
            {
                //建行端此笔款状态
                //var sate = XMLToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                //_logger.LogInformation($"充值成功[{orders_id}]->: ORDER_STATUS:" + sate);

                //if (sate == "1")
                {
                    book.status = "1";
                    book.update_time = dt;
                    SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();

                    var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == book.item_id);
                    var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);
                    var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(x => x.pat_id == book.pat_id);
                    //if (patient == null)
                    //{
                    //    return (Result.fail("患者信息异常！"));
                    //}
                    order_info order_ =SqlSugarFactory.Instance.Queryable<order_info>().First(x => x.orders_id == book.orders_id);
                    if (order_==null)
                    {
                        order_ = new order_info
                        {
                            pay_time = dt,
                            pat_id = book.pat_id,
                            appo_id = book.appo_id,
                            item_id = book.item_id,
                            price = item.price,
                            num = itemtype.num,
                            orders_id = book.orders_id,
                            wx_order_no = "建行",
                            status = "0",
                            invoiceStatus = 0
                        };
                        if (patient != null)
                        {
                            order_.tel = patient.tel;
                            order_.idnum = patient.idnum;
                            order_.pat_name = patient.name;
                        }
                        SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                        _logger.LogInformation($"[{orders_id}]->充值成功->写入数据库");
                    }
                    

                    //申请电子发票
                    if (patient != null)
                    {
                        _logger.LogInformation($"[{orders_id}]->充值成功->申请发票");

                        mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                        {
                            einvoicespecimen = "1",
                            issuedate = dt.ToString("yyyyMMdd"),
                            issuetime = dt.ToString("hh:mm:ss"),
                            payerpartytype = "1",
                            payerpartyname = patient.name,
                            totalamount = double.Parse(item.price.ToString()).ToString(),
                            bizcode = orders_id,
                            handlingperson = hebczConst.handlingperson,
                            checker = hebczConst.checker,
                            fundpayamount = "0",
                            otherpayamount = "0",
                            accountpayamount = "0",
                            ownpayamount = double.Parse(item.price.ToString()).ToString(),
                            //relatedinvoicecode = "1253",
                            //relatedinvoicenumber = orders_id,
                        };
                        model.details.Add(new details
                        {
                            itemcode = hebczConst.item_code,
                            itemname = hebczConst.item_name,
                            itemamount = double.Parse(item.price.ToString()).ToString(),

                        });
                        model.auxdetails.Add(new auxdetails
                        {
                            auxitemrelatedcode = hebczConst.item_code,
                            auxitemrelatedname = hebczConst.item_name,
                            auxitemname = item.name,
                            auxitemamount = double.Parse(item.price.ToString()).ToString()
                        });
                        HttpHelperMin http = new HttpHelperMin();
                        HttpItemMin httpitem = new HttpItemMin()
                        {
                            URL = hebczConst.Url + "/mkomedicaleinvoice",
                            Method = "POST",
                            ContentType = "application/json",
                            Postdata = JsonConvert.SerializeObject(model),
                        };
                        var resule = http.GetHtml(httpitem);
                        _logger.LogInformation($"[{orders_id}]->充值成功->申请发票返回:" + resule.Html);

                        var invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);
                        if (invStatus != null && invStatus.code == 1)
                        {
                            //查询开票状态
                            invStatus = hebczUtil.invoicestatus(orders_id);
                            _logger.LogInformation($"[{orders_id}]->充值成功->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                            //如果没有获取过，申请电子发票
                            if (invStatus != null && invStatus.code == 1 && invStatus.data.Count > 0 && invStatus.data[0].state != "0")
                            {
                                order_.einvoicecode = invStatus.data[0].einvoicecode;
                                order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                                order_.randomnumber = invStatus.data[0].randomnumber;
                                order_.invoiceStatus = 1;
                                SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                            }

                        }
                    }
                }
            }


            _logger.LogInformation($"[{orders_id}]->Action[PaySuccess]->---------结束------------");
            return Result.success();
        }
        /// <summary>
        /// 发起建行支付
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Pay")]
        public Result Pay(BankPayInput input)
        {
            _logger.LogInformation($"[{input.orders_id}]充值订单--开始------------------------------------");

            if (string.IsNullOrEmpty(input.code))
            {
                _logger.LogInformation($"[{input.orders_id}]充值订单:您拒绝了授权");
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return (Result.fail("您拒绝了授权！"));
            }

            //通过，用code换取access_token
            var appid = ConfigurationUtil.GetSection("Bank:WeixinAppId");
            var appSecret = ConfigurationUtil.GetSection("Bank:WeixinAppSecret");
            //获取openid
            string rMsg = string.Empty;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            try
            {
                httpRequest =
                       WebRequest.Create(
                               $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={appSecret}&code={input.code}&grant_type=authorization_code")
                        as HttpWebRequest;
                httpRequest.Method = "GET";
                httpRequest.ContentType = "text/html";
                //接收响应数据
                httpResponse = httpRequest.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(httpResponse.GetResponseStream(),
                        System.Text.Encoding.GetEncoding("UTF-8"));
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    rMsg = reader.ReadToEnd();
                    reader.Dispose();
                }
            }
            catch (Exception e)
            {
                _logger.LogInformation($"[{input.orders_id}]充值订单:" + "网络异常:" + e.Message);
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return Result.fail("网络异常:" + e.Message);
            }
            finally
            {
                httpRequest = null;
                httpResponse = null;
            }
            var m = Newtonsoft.Json.JsonConvert.DeserializeObject<wxcodecs>(rMsg);
            if (string.IsNullOrWhiteSpace(rMsg))
            {
                _logger.LogInformation($"[{input.orders_id}]充值订单:" + "无法获取openid:");
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return Result.fail("无法获取openid");
            }
            if (m == null || string.IsNullOrWhiteSpace(m.openid))
            {
                return Result.fail("微信异常:" + rMsg);
            }


            var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == input.orders_id);
            if (book == null || book.status != "0")
            {
                _logger.LogInformation($"[{input.orders_id}]充值订单:" + "预约信息异常:");
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return (Result.fail("预约信息异常！"));
            }
            var item = SqlSugarFactory.Instance.Queryable<check_item>().First(x => x.item_id == book.item_id);
            if (item == null)
            {
                _logger.LogInformation($"[{input.orders_id}]充值订单:" + "检查项目异常:");
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return (Result.fail("检查项目异常！"));
            }
            var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(x => x.pat_id == book.pat_id);
            if (patient == null)
            {
                _logger.LogInformation($"[{input.orders_id}]充值订单:" + "患者信息异常:");
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return (Result.fail("患者信息异常！"));
            }
            var JHPay = new BankParam()
            {
                MERCHANTID = "105000080621951",
                //POSID = "034631259",
                POSID = ConfigurationUtil.GetSection("Bank:POSID"),//"034631259",
                BRANCHID = ConfigurationUtil.GetSection("Bank:BRANCHID"),//"130000000",
                ORDERID = book.orders_id,
                //double.Parse(order.price.ToString()).ToString()
                PAYMENT = double.Parse(item.price.ToString()).ToString(),//item.price.ToString("##.##"),//"金额后不能再出现0,比如19.700"
                CURCODE = "01",
                REMARK1 = patient.idnum,//m.openid,
                REMARK2 = patient.idnum,
                TXCODE = ConfigurationUtil.GetSection("Bank:TXCODE"),//"530590",
                TYPE = "1",
                PUB = ConfigurationUtil.GetSection("Bank:PUB"),//"c6077ec51863c76522fe66e7020111",
                GATEWAY = "0",
                CLIENTIP = Request.Host.Host,
                REGINFO = patient.tel + "-" + patient.idnum,//patient.name + "-" + patient.tel + "-" + patient.idnum,
                PROINFO = patient.idnum,
                REFERER = ConfigurationUtil.GetSection("Bank:REFERER"),
                TIMEOUT = DateTime.Now.AddMinutes(5).ToString("yyyyMMddHHmmss"),
                TRADE_TYPE = "JSAPI",
                SUB_APPID = appid,
                SUB_OPENID = m.openid,
                // MAC = "b2a1adfc9f9a44b57731440e31710740"
                // MAC = "4e82b5b7b1c82c2e618c4070233b307b",
            };
            string mac = "MERCHANTID=" + JHPay.MERCHANTID + "&POSID=" + JHPay.POSID + "&BRANCHID=" + JHPay.BRANCHID +
                        "&ORDERID=" + JHPay.ORDERID + "&PAYMENT=" + JHPay.PAYMENT + "&CURCODE=01&TXCODE=530590&REMARK1=" + JHPay.REMARK1 +
                        "&REMARK2=" + HttpUtility.UrlEncodeUnicode(JHPay.REMARK2)/*JHPay.REMARK2*/ + "&TYPE=1&PUB=" + JHPay.PUB + "&GATEWAY=0&CLIENTIP=" + JHPay.CLIENTIP + "&REGINFO=" + HttpUtility.UrlEncodeUnicode(JHPay.REGINFO) +
                        "&PROINFO=" + JHPay.PROINFO + "&REFERER=&TIMEOUT=" + JHPay.TIMEOUT +
                        "&TRADE_TYPE=" + JHPay.TRADE_TYPE + "&SUB_APPID=" + JHPay.SUB_APPID + "&SUB_OPENID=" + JHPay.SUB_OPENID;
            _logger.LogInformation($"充值订单[{input.orders_id}]->mac:" + mac);

            JHPay.MAC = Md5.Get32MD5(mac).ToLower();
            //JHPay.MAC=  Common.CalcMD5(mac).ToLower();
            string data = NFine.Code.HttpMethods.HttpPost("https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain",
            "CCB_IBSVersion=V6&MERCHANTID=" + JHPay.MERCHANTID + "&POSID=" + JHPay.POSID + "&BRANCHID=" + JHPay.BRANCHID +
                        "&ORDERID=" + JHPay.ORDERID + "&PAYMENT=" + JHPay.PAYMENT + "&CURCODE=01&TXCODE=530590&REMARK1=" + JHPay.REMARK1 +
                        "&REMARK2=" + HttpUtility.UrlEncodeUnicode(JHPay.REMARK2)/*JHPay.REMARK2*/ + "&TYPE=1&GATEWAY=0&CLIENTIP=" + JHPay.CLIENTIP + "&REGINFO=" + HttpUtility.UrlEncodeUnicode(JHPay.REGINFO) +
                        "&PROINFO=" + JHPay.PROINFO + "&REFERER=&TIMEOUT=" + JHPay.TIMEOUT + "&TRADE_TYPE=" + JHPay.TRADE_TYPE +
                        "&SUB_APPID=" + JHPay.SUB_APPID + "&SUB_OPENID=" + JHPay.SUB_OPENID +
                        "&MAC=" + JHPay.MAC);
            _logger.LogInformation($"[{input.orders_id}]充值订单->建行返回:" + data);
            JObject jsonData = NFine.Code.Json.ToJObject(data);

         
            TemplateApi.SendTemplateMessage(AppId,
             m.openid, "QJM7zs35eByqO7Ys4lzeDCa6354wzRoIJgKYl2-GzVM", ConfigurationUtil.GetSection("Bank:MsgUrl") + input.orders_id,
              new
              {
                  first = new TemplateData { value = "点击获取预约码", color = "#000000" },
                  keyword1 = new TemplateData { value = patient.name, color = "#000000" },
                  keyword2 = new TemplateData { value = item.name, color = "#000000" },
                  keyword3 = new TemplateData { value = "二院停车场南端核酸采集点", color = "#000000" },
                  keyword4 = new TemplateData { value = DateTime.Now.ToString("yyyy-MM-dd"), color = "#000000" },
                  remark = new TemplateData { value = "", color = "#000000" }
              });

            if (jsonData.GetValue("SUCCESS").ToBool())
            {
                //ViewBag.pay = JsonConvert.SerializeObject(JHPay);
                //data = HttpMethods.HttpGet(jsonData.GetValue("PAYURL").ToString());
                //var WX = JsonConvert.DeserializeObject<BankResult>(data);
                //ViewBag.JHPay = JsonConvert.SerializeObject(WX);
                
                var pay = JsonConvert.SerializeObject(JHPay);
                _logger.LogInformation($"[{input.orders_id}]充值订单:返回->pay:" + pay);

                data = NFine.Code.HttpMethods.HttpGet(jsonData.GetValue("PAYURL").ToString());
                var WX = JsonConvert.DeserializeObject<BankResult>(data);
                var JHPayw = JsonConvert.SerializeObject(WX);
                _logger.LogInformation($"[{input.orders_id}]充值订单:返回->JHPayw:" + JHPayw);
               
                //判断是否已经支付过了
                if (WX!=null&&WX.ERRCODE == "0130Z1109001")
                {
                    DateTime dt = DateTime.Now;
                    book.status = "1";
                    book.update_time = dt;
                    SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();

                    var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);
                    order_info order_ = new order_info
                    {
                        pay_time = dt,
                        pat_id = book.pat_id,
                        appo_id = book.appo_id,
                        item_id = book.item_id,
                        price = item.price,
                        num = itemtype.num,
                        orders_id = book.orders_id,
                        wx_order_no = "建行",
                        status = "0",
                        invoiceStatus = 0
                    };
                    if (patient != null)
                    {
                        order_.tel = patient.tel;
                        order_.idnum = patient.idnum;
                        order_.pat_name = patient.name;
                    }
                    SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                    _logger.LogInformation($"[{input.orders_id}]->充值成功->写入数据库");
                    _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                    return Result.fail(WX.ERRMSG);
                }
              
                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return Result.success(new { mac, pay, data, JHPayw });
            }
            else
            {

                _logger.LogInformation($"[{input.orders_id}]充值订单--结束------------------------------------");
                return Result.success(new { mac, data });
            }

        }
    }
}
